// src/features/members/api/use-update-member.ts
import {useCallback, useMemo, useState} from "react";
import {MARK_DATA_URL} from "@/lib/social/constants";
import {Role} from "@/lib/social/types";

type Options = {
    onSuccess?: (id: string) => void
    onError?: (error: Error) => void
    onSettled?: () => void
    throwError?: boolean
}

type RequestType = {
    id: string
    role: Role
} | null

type ResponseType = {
    id: string
} | null


// client
export const useUpdateMember = () => {
    const [data, setData] = useState<ResponseType>(null)
    const [error, setError] = useState<Error | null>(null)
    const [status, setStatus] =
        useState<"success" | "error" | "settled" | "pending" | null>()

    const isPending = useMemo(() => status === 'pending', [status])
    const isSuccess = useMemo(() => status === 'success', [status])
    const isSettled = useMemo(() => status === 'settled', [status])
    const isError = useMemo(() => status === 'error', [status])

    const mutate = useCallback(async (values: RequestType, options?: Options) => {
        try {
            setData(null)
            setError(null)
            setStatus('pending')

            // if (values?.role !== 'admin') {
            //     return
            // }

            // const res = await fetch(`${MARK_DATA_URL}/members/${values?.id}`, {
            const res = await fetch(`/api/members/${values?.id}`, {
                    method: 'PATCH',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        role: values?.role,
                    })
                }
            )
            if (res.ok) {
                setStatus('success')
                // @ts-ignore
                setData(values?.id)
                options?.onSuccess?.(values?.id!)
            }
            return values?.id
        } catch (error) {
            setStatus('error')
            options?.onError?.(error as Error)
            if (options?.throwError) throw error
        } finally {
            setStatus("settled")
            options?.onSettled?.()
        }
    }, []);

    return {
        mutate, error, isPending, isSuccess, isSettled, isError, data
    }
}